package com.doughit.music163.core;

import com.doughit.music163.config.Config;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.doughit.music163.config.Config.DRIVER;

public class PlaylistNumberIncrease implements Increase {
    private static final Logger logger = LoggerFactory.getLogger(TotalNumberIncrease.class);
    //歌曲列表id
    private List<String> playListIds = Config.PLAY_LIST_IDS;

    private static ChromeOptions chromeOptions = new ChromeOptions();
    private static WebDriver driver = null;

    static {
        System.setProperty("webdriver.chrome.driver", DRIVER);
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("headless");
    }

    @Override
    public void start() {
        try {
            driver = new ChromeDriver(chromeOptions);
            invoke();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            driver.quit();
        }
    }

    /**
     * 初始化cookies
     */
    private static void initCookies() {
//        while (true) {
        try {
            JsonArray ja = (JsonArray) new JsonParser().parse(new FileReader("cookies.txt"));
            driver.manage().deleteAllCookies();
            ja.forEach(jsonElement -> {
                JsonObject jo = (JsonObject) jsonElement;
                Cookie cookie = new Cookie.Builder(jo.get("name").getAsString(), jo.get("value").getAsString()).build();
                driver.manage().addCookie(cookie);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
//        }
    }

    private void invoke() {
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
        String s = null;
        driver.get("http://music.163.com/");
        initCookies();
        Actions actions = new Actions(driver);
        while (true) {
            try {
                for (String playListId : playListIds) {
                    driver.get("https://music.163.com/#/playlist?id=" + playListId);
                    driver.switchTo().frame("contentFrame");
                    WebElement element = driver.findElement(By.cssSelector("[id=content-operation]>a:first-child"));
                    element.click();
                    s = driver.getPageSource();
                    String playlist = group(s, "<h2 class=\"f-ff2 (.*?)\">(.*?)</h2>", 2);
                    String times = driver.findElement(By.id("play-count")).getText();
                    logger.info("---当前播放歌单：" + playlist + ", 听歌次数:" + times);
                    Thread.sleep(1000L * Config.LIST_INTERVAL);
                }
                actions.sendKeys("P").perform();
                int left = Config.RECYCLE_LIST_INTERVAL - playListIds.size() * Config.LIST_INTERVAL;
                if (left >= 0) {
                    Thread.sleep(1000L * left);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    public static String group(String str, String regex, int index) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.find() ? matcher.group(index) : "";
    }
}
